package rsj.dao;

import com.rlyy.aibase.utils.base.Node;

import java.sql.Connection;

public class OrgPStatusDao extends BaseDao{
    private static final  OrgPStatusDao instance = new  OrgPStatusDao();
    public static  OrgPStatusDao getInstance() {
        return instance;
    }

    private static final String tableName = "sys.sys_status";
    private static final String allColumns = "sta_org_id,sta_prod_id,sta_status,sta_orgp_id";

    public void insertOrUpdateStatus(String prodId, String orgId, String applyStatus, Connection conn, String orgPId) {
        Node node = getByOrgAndProdId(prodId, orgId, conn);
        if(node != null && node.valueInt() > 0){
            updateStatus(conn, prodId, orgId, applyStatus, orgPId);
        } else {
            insertStatus(conn, prodId, orgId, applyStatus, orgPId);
        }

    }

    // sta_org_id,sta_prod_id,sta_status,sta_orgp_id
    private void insertStatus(Connection conn, String prodId, String orgId, String applyStatus, String orgPId) {
        String sql = String.format(insertSql, tableName, allColumns, "?,?,?,?");
        getQueryRunner().update(conn, sql, orgId, prodId, applyStatus, orgPId);
    }

    private void updateStatus(Connection conn, String prodId, String orgId, String applyStatus, String orgPId) {
        String sql = String.format(updateSql, tableName, " sta_status = ? ,sta_orgp_id = ? ", " sys_status.sta_org_id = ?" +
                " and sys_status.sta_prod_id = ? ");
        getQueryRunner().update(conn, sql, applyStatus, orgPId, orgId, prodId);
    }

    public Node getByOrgAndProdId(String prodId, String orgId, Connection conn){
        String sql = String.format(select, " count(1) " , tableName, " sta_prod_id = ? and sta_org_id = ? ");
        return getQueryRunner().queryLinkNode(conn, sql, prodId, orgId);
    }
}
